﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Net;
using System.Net.Mail;
using System.Net.Configuration;
using OsPortal;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Text;
using System.Xml;
using System.Web.Caching;


/// <summary>
/// Summary description for clsCommon
/// </summary>
/// 


public static class basConst
{
    public const string POSTSIGN = "99999999";
    public const string PR_USERCONTROL_NAME = "mo";

    //Thời gian sống của cache
    public const int timeCache = 30;
    //Thời gian sống của cookie 30 ngay
    public const int timeCookie = 30;

    //Cookie
    public const string COOKIE_USER_INFO = "userInfo_cookie";
    public const string COOKIE_USER_ID = "US_ID";
    public const string COOKIE_USER_NAME = "us_hoten";
    public const string COOKIE_USER_EMAIL = "us_email";
    public const string COOKIE_USER_LASTLOGIN = "us_lastlogin";

    //QueryString
    public const string QR_URL_REDERECT = "rturl";
    public const string QR_URL_PTID = "pt_id";

    //MOD-ACTION====================================================
    public const string MOD_ADD = "A";
    public const string MOD_UPDATE = "U";
    public const string MOD_DELETE = "D";
    public const string MOD_CHANGE = "C";

    // TRANG HIỆN TẠI
    public const int CURENT_PAGE = 1;
    //So luong san pham / 1 trang
    public const int PROC_NUMBER = 20;
    public const int NEWS_NUMBER = 2;
    //Message system
    public const string DATAISNULL="Không có dữ liệu";
    //Duong dan luu tru
    public const string PATH_IMAGES_USER = "~/Images/UsersUpload/";

    // ĐƯỜNG DẪN LƯU TRỮ FILE TEXT
    public const string LinkFormMailActiveAccount = "SaveFile/FormMailActiveAccount.txt";
    public const string LinkFormGetPassword = "SaveFile/FormGetPassWord.txt";
    public const string LinkFormMailGopY = "SaveFile/FormMailGopY.txt";
    //
    public const string PT_TOAN_QUOC = "toan-quoc";
    //
    public const string KP_TAT_CA = "cho-thue-phong-tro-nha-tro";
    public static string[] gstrNhaMangGameBank = { "", "Viettel", "Mobifone", "Vinaphone", "Gate", "VTC" };
}
/*------------------------------------------------------------*/


public static class clsCommon
{
    static string strClassName = "clsCommon";

    /// <summary>
    /// Lấy IP của máy đang truy cập
    /// </summary>
    /// <returns></returns>
    public static string fncGetClientIP()
    {
        string ipList = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (!string.IsNullOrEmpty(ipList))
        {
            return ipList.Split(',')[0];
        }

        return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    }

    /// <summary>
    /// Get Route
    /// </summary>
    /// <param name="objPage">this.Page</param>
    /// <param name="strParam">Param</param>
    /// <returns></returns>
    public static string fncGetRoute(System.Web.UI.Page objPage, string strParam)
    {
        return OsPortal.oStringHelper.fncCnvNullToString(objPage.RouteData.Values[strParam]);
    }

    /// <summary>
    /// Tự động load UserControl
    /// </summary>
    /// <param name="plhControl">PlaceHolderID</param>
    /// <param name="objPage">This.Page</param>
    /// <param name="strFolderUrl">Thư mục chứa userControl</param>
    /// <param name="strUCDefault">UserControl mặc định</param>
    public static void fncLoadUserControl(PlaceHolder plhControl, System.Web.UI.Page objPage, string strFolderUrl, string strUCDefault)
    {
        string Param = HttpContext.Current.Request.QueryString.Get(basConst.PR_USERCONTROL_NAME);
        fncLoadUserControl(plhControl, objPage, strFolderUrl, Param, strUCDefault);
    }

    /// <summary>
    /// Tự động load UserControl
    /// </summary>
    /// <param name="plhControl">PlaceHolderID</param>
    /// <param name="objPage">This.Page</param>
    /// <param name="strFolderUrl">Thư mục chứa userControl</param>
    /// <param name="strUCDefault">UserControl mặc định</param>
    public static void fncLoadUserControl(PlaceHolder plhControl, System.Web.UI.Page objPage, string strFolderUrl, string strControName, string strUCDefault)
    {
        string Param = strControName;
        try
        {
            if (!string.IsNullOrEmpty(Param))
            {
                string str = strFolderUrl + Param.ToString() + ".ascx";
                plhControl.Controls.Add(objPage.LoadControl(str));
            }
            else
            {
                Param = strUCDefault;
                string str = strFolderUrl + Param.ToString() + ".ascx";
                plhControl.Controls.Add(objPage.LoadControl(str));
            }
        }
        catch (Exception ex)
        {
            OsPortal.oFileHelper.WriteLogErr(strClassName, "fncLoadUserControl()", ex.ToString());
            HttpContext.Current.Response.Redirect("/404");
        }
    }


    /// <summary>
    /// Tự động tạo mã để insert vào CSDL
    /// </summary>
    /// <param name="strTienTo">Tiền Tố Của Mã VD: TD</param>
    /// <param name="strTenBang">Tên bảng</param>
    /// <param name="strTenKhoaChinh">Tên khóa chính</param>
    /// <returns></returns>
    public static string fncAutoCreateID(string strTienTo, string strTenBang, string strTenKhoaChinh)
    {
        DataTable dt = oSqlDataHelper.sExecuteDataTable("select max(" + strTenKhoaChinh + ") 'id' from " + strTenBang + "", null);
        Console.Write(dt.Rows.Count);

        try
        {
            string strMaCuoiCung = dt.Rows[0]["id"].ToString();
            string kq = "";
            int so = int.Parse(strMaCuoiCung.Substring(2));
            if (so + 1 < 999999)
                kq = strTienTo + (so + 1);
            if (so + 1 < 100000)
                kq = strTienTo + "0" + (so + 1);
            if (so + 1 < 10000)
                kq = strTienTo + "00" + (so + 1);
            if (so + 1 < 1000)
                kq = strTienTo + "000" + (so + 1);
            if (so + 1 < 100)
                kq = strTienTo + "0000" + (so + 1);
            if (so + 1 < 10)
                kq = strTienTo + "00000" + (so + 1);

            return kq;
        }
        catch (Exception ex)
        {
            OsPortal.oFileHelper.WriteLogErr(strClassName, "fncAutoCreateID", ex.ToString());
            return strTienTo + "000001";
        }
    }

    /// <summary>
    /// Trả về phần đầu của chuỗi và đảm bảo đủ từ
    /// </summary>
    /// <param name="s"></param>
    /// <param name="length">Số ký tự tối đa được cắt</param>
    /// <returns>Chuoi can cat</returns>
    public static string fncCatChuoi(string s, int length)
    {
        if (String.IsNullOrEmpty(s))
            return "";
        var words = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
        if (words[0].Length > length)
            return s;
        var sb = new StringBuilder();
        foreach (var word in words)
        {
            if ((sb + word).Length > length)
                return string.Format("{0}...", sb.ToString().TrimEnd(' '));
            sb.Append(word + " ");
        }
        return string.Format("{0}...", sb.ToString().TrimEnd(' '));
    }

    /// <summary>
    /// Lấy một chuỗi ngẫu nhiên
    /// </summary>
    /// <param name="codeCount">Số lượng ký tự</param>
    /// <returns></returns>
    public static string NgauNhien_SoChu(int codeCount)
    {
        string allChar = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
        string[] allCharArray = allChar.Split(',');
        string randomCode = "";
        int temp = -1;

        Random rand = new Random();
        for (int i = 0; i < codeCount; i++)
        {
            if (temp != -1)
            {
                rand = new Random(i * temp * ((int)DateTime.Now.Ticks));
            }
            int t = rand.Next(36);
            if (temp != -1 && temp == t)
            {
                return NgauNhien_SoChu(codeCount);
            }
            temp = t;
            randomCode += allCharArray[t];
        }
        return randomCode;
    }

}

/*---------------------public calss expost HTLML------------------*/
public class clsExportHtml
{
    static string strClassName = "clsExportHtml";
    /// <summary>
    /// Export HTML danh sách phòng trọ
    /// Author: ThuanNH
    /// Create Date: 2013/08/01
    /// </summary>
    /// <param name="dtSource"></param>
    /// <returns></returns>
    public static string fncExportPhongTro(DataTable dtSource)
    {
        StringBuilder sbHtml = new StringBuilder("");
        try
        {
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                string strPT_ID = dtSource.Rows[i]["PT_ID"].ToString().ToLower();
                string strPT_TIEUDE = dtSource.Rows[i]["PT_TIEUDE"].ToString();
                string strTIEUDEKHONGDAU = dtSource.Rows[i]["PT_TIEUDEKHONGDAU"].ToString();
                string strPT_DIACHI = dtSource.Rows[i]["PT_DIACHI"].ToString();
                string strPT_GIAPHONG = String.Format("{0:0,0 vnđ}", dtSource.Rows[i]["PT_GIAPHONG"]);
                string strPT_DIENTICH = String.Format("{0:0,0 m2}", dtSource.Rows[i]["PT_DIENTICH"]);
                string strPT_LUOTXEM = dtSource.Rows[i]["PT_LUOTXEM"].ToString();
                string strPT_NGAYCAPNHAT = String.Format("{0:dd/MM/yyyy}", Convert.ToDateTime(dtSource.Rows[i]["PT_NGAYCAPNHAT"]));
                string strPT_KIEUPHONG = dtSource.Rows[i]["KP_TENKHONGDAU"].ToString().ToLower();
                string strPT_KHUVUC = dtSource.Rows[i]["KV_TENKHONGDAU"].ToString().ToLower();
                string strKP_ICON = dtSource.Rows[i]["KP_ICON"].ToString();
                string strKP_COLOR = dtSource.Rows[i]["KP_COLOR"].ToString();
                string strKV_TEN = dtSource.Rows[i]["KV_TEN"].ToString();
                //
                string strMotaCT = OsPortal.oStringHelper.ClearTagHTML(dtSource.Rows[i]["pt_motachitiet"].ToString());
                strMotaCT = OsPortal.oStringHelper.CatChuoi(strMotaCT, 350);
                strMotaCT = strMotaCT.Replace("\r", "");
                strMotaCT = strMotaCT.Replace("\n", "");  
                //
                string strURL = "/" + strPT_KIEUPHONG + "/" + strPT_KHUVUC + "/" + strTIEUDEKHONGDAU + "-" + strPT_ID;
                //
                sbHtml.Append("<div class='lstRow'>");
                sbHtml.Append("<div class='lstCTleft' style='background-color: " + strKP_COLOR + "'>");
                sbHtml.Append("<img alt='" + strPT_TIEUDE + "' src='http://xomtrosv.com/" + strKP_ICON + "'></div>");
                sbHtml.Append("<div class='lstMid'>");
                sbHtml.Append("<h3><a class='title' href='" + strURL + "'>" + strPT_TIEUDE + " - <span style='color:#808080;'>" + strPT_NGAYCAPNHAT + "</span></a></h3>");
                sbHtml.Append("<p style='font-size: 12px;'><b>Địa chỉ:</b> <b>[<span style='color: Red;'>" + strKV_TEN + "</span>]</b> " + strPT_DIACHI + "</p>");
                sbHtml.Append("<p style='font-size: 12px;'><b>Giá phòng:</b> <span style='color: Red;'>" + strPT_GIAPHONG + "</span> | <b>Diện tích:</b> " + strPT_DIENTICH + " | " + strPT_LUOTXEM + " lượt xem</p>");
                sbHtml.Append("</div>");
                sbHtml.Append("<div class='clr'></div>");
                sbHtml.Append("</div>");
            }
        }
        catch (Exception ex)
        {
            OsPortal.oFileHelper.WriteLogErr(strClassName, "fncExportPhongTro", ex.ToString());
        }
        return sbHtml.ToString();
    }

    /// <summary>
    /// Export HTML Khu vực dropdownlist
    /// Author: ThuanNH
    /// CreateDate: 25/09/2013
    /// </summary>
    /// <param name="dtSource"></param>
    /// <returns></returns>
    public static string fncExportKhuVuc_DropDownList(DataTable dtSource, int iType)
    {
        string html = "";
        try
        {
            if (iType == 1)
                html += "<option kinhdo='0' vido='0' value='0'>==Chọn quận huyện==</option>";
            for (int i = 0; i < dtSource.Rows.Count; i++)
            {
                string strKV_ID = dtSource.Rows[i]["KV_ID"].ToString().ToLower();
                string strKV_ten = dtSource.Rows[i]["kv_ten"].ToString();
                string strKV_tenkhongdau = dtSource.Rows[i]["kv_tenkhongdau"].ToString().ToLower();
                string strkv_kinhdo = dtSource.Rows[i]["kv_kinhdo"].ToString();
                string strkv_vido = dtSource.Rows[i]["kv_vido"].ToString();

                string strValue = strKV_ID;
                if (iType == 1) strValue = strKV_tenkhongdau;

                html += "<option kinhdo='" + strkv_kinhdo + "' vido='" + strkv_vido + "' value='" + strValue + "'>" + strKV_ten + "</option>";
            }
        }
        catch (Exception ex)
        {

            OsPortal.oFileHelper.WriteLogErr(strClassName, "fncExportTinhThanh_Popup", ex.ToString());
        }

        return html;
    }
}